/**
 * Description:
 * Class Name:FileChannelTest
 * Date:2022/5/3 17:50
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第15章_输入输出._15_9_NIO._15_9_3_使用Channel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class FileChannelTest {
    public static void main(String[] args) {
        String path = "./src/" + FileChannelTest.class.getName().replace(".", "/") + ".java";
        File f = new File(path);
        try (
                var inChannel = new FileInputStream(f).getChannel();
                var outChannel = new FileOutputStream("Chapter_15_9_3_useChannel.txt").getChannel()
                ){
            // 将FileChannel里的全部数据映射成ByteBuffer
            MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, f.length());      // ①
            // 使用GBK的字符集来创建解码器
            Charset charset = Charset.forName("GBK");
            // 直接将buffer里的数据全部输出
            outChannel.write(buffer);                               // ②
            // 再次调用buffer的clear()方法，复原limit、position的位置
            buffer.clear();
            // 创建解码器（CharsetDecoder）对象
            CharsetDecoder decoder = charset.newDecoder();
            // 使用解码器将ByteBuffer转换成CharBuffer
            CharBuffer charBuffer = decoder.decode(buffer);
            // CharBuffer的toString()方法可以获取对应的字符串
            System.out.println(charBuffer);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}
